<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据备份与恢复</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(45deg, #FF6B6B, #4ECDC4);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }

        .content {
            padding: 30px;
        }

        .section {
            margin-bottom: 30px;
            padding: 25px;
            background: #f8f9fa;
            border-radius: 10px;
            border-left: 4px solid #4ECDC4;
        }

        .section h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 20px;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            margin-right: 10px;
            margin-bottom: 10px;
        }

        .btn-primary {
            background: linear-gradient(45deg, #4ECDC4, #44A08D);
            color: white;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-warning {
            background: #ffc107;
            color: #212529;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        .file-input {
            margin: 15px 0;
        }

        .file-input input[type="file"] {
            padding: 10px;
            border: 2px dashed #4ECDC4;
            border-radius: 8px;
            width: 100%;
            background: white;
        }

        .backup-info {
            background: #e3f2fd;
            padding: 20px;
            border-radius: 8px;
            margin: 15px 0;
            border-left: 4px solid #2196f3;
        }

        .backup-list {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            margin-top: 15px;
        }

        .backup-item {
            padding: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .backup-item:last-child {
            border-bottom: none;
        }

        .backup-details {
            flex: 1;
        }

        .backup-name {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .backup-meta {
            font-size: 14px;
            color: #666;
        }

        .status {
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
            font-weight: bold;
        }

        .status.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .status.info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .progress {
            width: 100%;
            height: 20px;
            background: #e9ecef;
            border-radius: 10px;
            overflow: hidden;
            margin: 10px 0;
        }

        .progress-bar {
            height: 100%;
            background: linear-gradient(45deg, #4ECDC4, #44A08D);
            transition: width 0.3s;
        }

        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 10px;
            }
            
            .header {
                padding: 20px;
            }
            
            .content {
                padding: 20px;
            }
            
            .btn {
                width: 100%;
                margin-right: 0;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>💾 数据备份与恢复</h1>
            <p>保护您的购销单数据安全</p>
        </div>

        <div class="content">
            <!-- 状态显示 -->
            <div id="statusMessage" style="display: none;"></div>

            <!-- 备份数据 -->
            <div class="section">
                <h2>📤 备份数据</h2>
                <p>将您的购销单数据导出为文件，可以保存到电脑或云盘中。</p>
                
                <div class="backup-info">
                    <strong>📊 当前数据统计：</strong>
                    <div id="dataStats">正在加载...</div>
                </div>

                <button class="btn btn-primary" onclick="exportData()">📥 导出所有数据</button>
                <button class="btn btn-success" onclick="exportCurrentOrder()">📋 导出当前订单</button>
                <button class="btn btn-warning" onclick="exportSettings()">⚙️ 导出设置</button>
            </div>

            <!-- 恢复数据 -->
            <div class="section">
                <h2>📥 恢复数据</h2>
                <p>从备份文件中恢复您的数据。支持JSON格式的备份文件。</p>
                
                <div class="file-input">
                    <input type="file" id="backupFile" accept=".json" onchange="handleFileSelect(event)">
                </div>

                <button class="btn btn-primary" onclick="importData()" disabled id="importBtn">📤 导入数据</button>
                <button class="btn btn-danger" onclick="clearAllData()">🗑️ 清空所有数据</button>
            </div>

            <!-- 自动备份 -->
            <div class="section">
                <h2>🔄 自动备份</h2>
                <p>设置自动备份，定期保存您的数据。</p>
                
                <div style="margin: 15px 0;">
                    <label>
                        <input type="checkbox" id="autoBackup" onchange="toggleAutoBackup()"> 
                        启用自动备份（每天一次）
                    </label>
                </div>

                <div id="autoBackupStatus" class="backup-info" style="display: none;">
                    <div>下次备份时间：<span id="nextBackupTime"></span></div>
                    <div>最后备份时间：<span id="lastBackupTime"></span></div>
                </div>

                <button class="btn btn-success" onclick="createManualBackup()">💾 立即备份</button>
            </div>

            <!-- 备份历史 -->
            <div class="section">
                <h2>📚 备份历史</h2>
                <p>查看和管理您的备份记录。</p>
                
                <div class="backup-list" id="backupHistory">
                    <div style="text-align: center; padding: 30px; color: #999;">
                        暂无备份记录
                    </div>
                </div>

                <button class="btn btn-warning" onclick="cleanOldBackups()">🧹 清理旧备份</button>
            </div>

            <!-- 云端同步 -->
            <div class="section">
                <h2>☁️ 云端同步</h2>
                <p>将数据同步到云端，实现跨设备访问。</p>
                
                <div class="backup-info">
                    <strong>🔗 同步状态：</strong>
                    <span id="syncStatus">未连接</span>
                </div>

                <button class="btn btn-primary" onclick="syncToCloud()">☁️ 同步到云端</button>
                <button class="btn btn-success" onclick="downloadFromCloud()">📥 从云端下载</button>
            </div>
        </div>
    </div>

    <script>
        let selectedFile = null;
        let autoBackupEnabled = false;

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            updateDataStats();
            loadAutoBackupSettings();
            loadBackupHistory();
            checkSyncStatus();
        });

        // 更新数据统计
        function updateDataStats() {
            try {
                const orderData = localStorage.getItem('purchaseOrderData');
                const syncCodes = Object.keys(localStorage).filter(key => key.startsWith('sync_'));
                const backups = Object.keys(localStorage).filter(key => key.startsWith('backup_'));

                let orderCount = 0;
                let itemCount = 0;

                if (orderData) {
                    const data = JSON.parse(orderData);
                    if (data.items) {
                        itemCount = data.items.length;
                        orderCount = 1;
                    }
                }

                document.getElementById('dataStats').innerHTML = `
                    <div>📋 订单数量: ${orderCount}</div>
                    <div>📦 商品条目: ${itemCount}</div>
                    <div>🔄 同步码: ${syncCodes.length}</div>
                    <div>💾 备份文件: ${backups.length}</div>
                `;
            } catch (error) {
                document.getElementById('dataStats').textContent = '数据统计失败';
            }
        }

        // 导出所有数据
        function exportData() {
            try {
                const allData = {};
                
                // 收集所有相关数据
                for (let key in localStorage) {
                    if (key.startsWith('purchaseOrder') || key.startsWith('sync_') || key.startsWith('backup_')) {
                        allData[key] = localStorage.getItem(key);
                    }
                }

                const dataStr = JSON.stringify(allData, null, 2);
                const blob = new Blob([dataStr], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                
                const a = document.createElement('a');
                a.href = url;
                a.download = `购销单备份_${new Date().toISOString().split('T')[0]}.json`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);

                showStatus('数据导出成功！', 'success');
                
                // 记录备份
                recordBackup('完整备份', Object.keys(allData).length);
            } catch (error) {
                showStatus('数据导出失败：' + error.message, 'error');
            }
        }

        // 导出当前订单
        function exportCurrentOrder() {
            try {
                const orderData = localStorage.getItem('purchaseOrderData');
                if (!orderData) {
                    showStatus('没有找到当前订单数据', 'error');
                    return;
                }

                const blob = new Blob([orderData], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                
                const a = document.createElement('a');
                a.href = url;
                a.download = `当前订单_${new Date().toISOString().split('T')[0]}.json`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);

                showStatus('当前订单导出成功！', 'success');
                recordBackup('订单备份', 1);
            } catch (error) {
                showStatus('订单导出失败：' + error.message, 'error');
            }
        }

        // 导出设置
        function exportSettings() {
            try {
                const settings = {
                    autoBackup: localStorage.getItem('autoBackupEnabled'),
                    lastBackup: localStorage.getItem('lastBackupTime'),
                    version: '1.0'
                };

                const dataStr = JSON.stringify(settings, null, 2);
                const blob = new Blob([dataStr], { type: 'application/json' });
                const url = URL.createObjectURL(blob);
                
                const a = document.createElement('a');
                a.href = url;
                a.download = `设置备份_${new Date().toISOString().split('T')[0]}.json`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);

                showStatus('设置导出成功！', 'success');
                recordBackup('设置备份', 1);
            } catch (error) {
                showStatus('设置导出失败：' + error.message, 'error');
            }
        }

        // 处理文件选择
        function handleFileSelect(event) {
            selectedFile = event.target.files[0];
            const importBtn = document.getElementById('importBtn');
            
            if (selectedFile && selectedFile.type === 'application/json') {
                importBtn.disabled = false;
                showStatus(`已选择文件: ${selectedFile.name}`, 'info');
            } else {
                importBtn.disabled = true;
                showStatus('请选择有效的JSON备份文件', 'error');
            }
        }

        // 导入数据
        function importData() {
            if (!selectedFile) {
                showStatus('请先选择备份文件', 'error');
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const data = JSON.parse(e.target.result);
                    
                    // 确认导入
                    if (!confirm('导入数据将覆盖现有数据，是否继续？')) {
                        return;
                    }

                    let importCount = 0;
                    
                    // 导入数据
                    for (let key in data) {
                        localStorage.setItem(key, data[key]);
                        importCount++;
                    }

                    showStatus(`数据导入成功！共导入 ${importCount} 项数据`, 'success');
                    updateDataStats();
                    
                    // 刷新页面以应用新数据
                    setTimeout(() => {
                        if (confirm('数据已导入，是否刷新页面以应用更改？')) {
                            location.reload();
                        }
                    }, 2000);
                    
                } catch (error) {
                    showStatus('数据导入失败：文件格式错误', 'error');
                }
            };
            
            reader.readAsText(selectedFile);
        }

        // 清空所有数据
        function clearAllData() {
            if (!confirm('确定要清空所有数据吗？此操作不可恢复！')) {
                return;
            }

            if (!confirm('最后确认：这将删除所有购销单数据、同步码和备份记录！')) {
                return;
            }

            try {
                // 清除相关数据
                const keysToRemove = [];
                for (let key in localStorage) {
                    if (key.startsWith('purchaseOrder') || key.startsWith('sync_') || key.startsWith('backup_')) {
                        keysToRemove.push(key);
                    }
                }

                keysToRemove.forEach(key => localStorage.removeItem(key));
                
                showStatus(`已清空 ${keysToRemove.length} 项数据`, 'success');
                updateDataStats();
                loadBackupHistory();
                
            } catch (error) {
                showStatus('清空数据失败：' + error.message, 'error');
            }
        }

        // 切换自动备份
        function toggleAutoBackup() {
            autoBackupEnabled = document.getElementById('autoBackup').checked;
            localStorage.setItem('autoBackupEnabled', autoBackupEnabled);
            
            const statusDiv = document.getElementById('autoBackupStatus');
            
            if (autoBackupEnabled) {
                statusDiv.style.display = 'block';
                updateAutoBackupStatus();
                scheduleAutoBackup();
                showStatus('自动备份已启用', 'success');
            } else {
                statusDiv.style.display = 'none';
                clearAutoBackup();
                showStatus('自动备份已禁用', 'info');
            }
        }

        // 加载自动备份设置
        function loadAutoBackupSettings() {
            autoBackupEnabled = localStorage.getItem('autoBackupEnabled') === 'true';
            document.getElementById('autoBackup').checked = autoBackupEnabled;
            
            if (autoBackupEnabled) {
                document.getElementById('autoBackupStatus').style.display = 'block';
                updateAutoBackupStatus();
                scheduleAutoBackup();
            }
        }

        // 更新自动备份状态
        function updateAutoBackupStatus() {
            const lastBackup = localStorage.getItem('lastBackupTime');
            const nextBackup = new Date(Date.now() + 24 * 60 * 60 * 1000);
            
            document.getElementById('lastBackupTime').textContent = 
                lastBackup ? new Date(lastBackup).toLocaleString() : '从未备份';
            document.getElementById('nextBackupTime').textContent = 
                nextBackup.toLocaleString();
        }

        // 安排自动备份
        function scheduleAutoBackup() {
            // 简化版：每次页面加载时检查是否需要备份
            const lastBackup = localStorage.getItem('lastBackupTime');
            const now = Date.now();
            
            if (!lastBackup || (now - parseInt(lastBackup)) > 24 * 60 * 60 * 1000) {
                createManualBackup();
            }
        }

        // 清除自动备份
        function clearAutoBackup() {
            // 这里可以清除定时器等
        }

        // 创建手动备份
        function createManualBackup() {
            try {
                const timestamp = Date.now();
                const allData = {};
                
                // 收集数据
                for (let key in localStorage) {
                    if (key.startsWith('purchaseOrder') || key.startsWith('sync_')) {
                        allData[key] = localStorage.getItem(key);
                    }
                }

                // 保存备份记录
                const backupRecord = {
                    id: timestamp,
                    name: `自动备份_${new Date(timestamp).toLocaleString()}`,
                    data: allData,
                    timestamp: timestamp,
                    size: JSON.stringify(allData).length,
                    type: 'auto'
                };

                localStorage.setItem(`backup_${timestamp}`, JSON.stringify(backupRecord));
                localStorage.setItem('lastBackupTime', timestamp.toString());
                
                showStatus('备份创建成功！', 'success');
                updateAutoBackupStatus();
                loadBackupHistory();
                
            } catch (error) {
                showStatus('备份创建失败：' + error.message, 'error');
            }
        }

        // 记录备份
        function recordBackup(name, itemCount) {
            const timestamp = Date.now();
            const record = {
                id: timestamp,
                name: name,
                timestamp: timestamp,
                itemCount: itemCount,
                type: 'manual'
            };
            
            localStorage.setItem(`backup_record_${timestamp}`, JSON.stringify(record));
            loadBackupHistory();
        }

        // 加载备份历史
        function loadBackupHistory() {
            const historyDiv = document.getElementById('backupHistory');
            const backups = [];
            
            // 收集备份记录
            for (let key in localStorage) {
                if (key.startsWith('backup_') || key.startsWith('backup_record_')) {
                    try {
                        const record = JSON.parse(localStorage.getItem(key));
                        backups.push(record);
                    } catch (error) {
                        // 忽略损坏的记录
                    }
                }
            }
            
            if (backups.length === 0) {
                historyDiv.innerHTML = '<div style="text-align: center; padding: 30px; color: #999;">暂无备份记录</div>';
                return;
            }
            
            // 按时间排序
            backups.sort((a, b) => b.timestamp - a.timestamp);
            
            historyDiv.innerHTML = backups.map(backup => `
                <div class="backup-item">
                    <div class="backup-details">
                        <div class="backup-name">${backup.name}</div>
                        <div class="backup-meta">
                            ${new Date(backup.timestamp).toLocaleString()} | 
                            ${backup.itemCount || 0} 项 | 
                            ${backup.type === 'auto' ? '自动' : '手动'}备份
                        </div>
                    </div>
                    <div>
                        <button class="btn btn-primary" onclick="restoreBackup(${backup.id})">恢复</button>
                        <button class="btn btn-danger" onclick="deleteBackup(${backup.id})">删除</button>
                    </div>
                </div>
            `).join('');
        }

        // 恢复备份
        function restoreBackup(backupId) {
            if (!confirm('恢复备份将覆盖当前数据，是否继续？')) {
                return;
            }
            
            try {
                const backupData = localStorage.getItem(`backup_${backupId}`);
                if (!backupData) {
                    showStatus('备份数据不存在', 'error');
                    return;
                }
                
                const backup = JSON.parse(backupData);
                
                // 恢复数据
                for (let key in backup.data) {
                    localStorage.setItem(key, backup.data[key]);
                }
                
                showStatus('备份恢复成功！', 'success');
                updateDataStats();
                
                setTimeout(() => {
                    if (confirm('数据已恢复，是否刷新页面以应用更改？')) {
                        location.reload();
                    }
                }, 2000);
                
            } catch (error) {
                showStatus('备份恢复失败：' + error.message, 'error');
            }
        }

        // 删除备份
        function deleteBackup(backupId) {
            if (!confirm('确定要删除这个备份吗？')) {
                return;
            }
            
            localStorage.removeItem(`backup_${backupId}`);
            localStorage.removeItem(`backup_record_${backupId}`);
            
            showStatus('备份已删除', 'info');
            loadBackupHistory();
        }

        // 清理旧备份
        function cleanOldBackups() {
            const cutoffTime = Date.now() - 30 * 24 * 60 * 60 * 1000; // 30天前
            let cleanedCount = 0;
            
            for (let key in localStorage) {
                if (key.startsWith('backup_') || key.startsWith('backup_record_')) {
                    try {
                        const record = JSON.parse(localStorage.getItem(key));
                        if (record.timestamp < cutoffTime) {
                            localStorage.removeItem(key);
                            cleanedCount++;
                        }
                    } catch (error) {
                        // 删除损坏的记录
                        localStorage.removeItem(key);
                        cleanedCount++;
                    }
                }
            }
            
            showStatus(`已清理 ${cleanedCount} 个旧备份`, 'success');
            loadBackupHistory();
        }

        // 同步到云端
        function syncToCloud() {
            showStatus('云端同步功能开发中...', 'info');
        }

        // 从云端下载
        function downloadFromCloud() {
            showStatus('云端下载功能开发中...', 'info');
        }

        // 检查同步状态
        function checkSyncStatus() {
            document.getElementById('syncStatus').textContent = '本地存储';
        }

        // 显示状态消息
        function showStatus(message, type) {
            const statusDiv = document.getElementById('statusMessage');
            statusDiv.className = `status ${type}`;
            statusDiv.textContent = message;
            statusDiv.style.display = 'block';
            
            setTimeout(() => {
                statusDiv.style.display = 'none';
            }, 5000);
        }
    </script>
</body>
</html>